<?php
/**
 * Each engineer has a duty to keep the code elegant
 * Created by wolffy.
 * Author @wolffy<13750088090@sina.cn>
 * Date: 2018/8/12
 * Time: 11:40
 */
namespace App\Repositories;

use App\Models\CollectMoneyBill;
use App\Models\User;
use App\Models\UserBankCard;
use App\Models\UserCreditCard;
use Illuminate\Support\Facades\DB;

class CollectMoneyBillRepository
{
    /**
     * 创建用户绑定的收银账单
     * @param array $params
     * @return mixed
     */
    public function create(array $params)
    {
        return CollectMoneyBill::create($params);
    }

    /**
     * 创建用户绑定的收银账单
     * @param array $params
     * @return mixed
     */
    public function insertGetId(array $params)
    {
        return CollectMoneyBill::insertGetId($params);
    }

    /**
     * 根据id获取收银账单资料
     * @param $id
     * @return mixed
     */
    public function byId($id)
    {
        return CollectMoneyBill::find($id);
    }

    public function findByBillSn($orderNo)
    {
        return CollectMoneyBill::where('bill_sn', $orderNo)->first();
    }

    public function findByBillSnIsSuccess($orderNo, $status)
    {
        return CollectMoneyBill::where([
            'bill_sn' => $orderNo,
            'collect_money_status' => $status,
        ])->first();
    }

    public function updateBillStatus($orderNo, $status, $failMessage = '')
    {
        return CollectMoneyBill::where('bill_sn', $orderNo)->update([
            'collect_money_status' => $status,
            'fail_message' => $failMessage,
            'update_collect_time' => time()
        ]);
    }

    public function groupByMonth($userId, $creditCardId, $collectMoneyStatus)
    {
        return CollectMoneyBill::select(DB::raw('create_month, sum(collect_money) as collect_money'))
            ->groupBy('create_month')
            ->where([
                'user_id' => $userId,
                'credit_card_id' => $creditCardId,
                'collect_money_status' => $collectMoneyStatus,
            ])
            ->orderBy('create_month', 'desc')
            ->get()->toArray();
    }

    public function getTradeRecord($month, $userId, $creditCardId)
    {
        return CollectMoneyBill::where([
            'create_month' => $month,
            'user_id' => $userId,
            'credit_card_id' => $creditCardId,
        ])
            ->orderBy('create_collect_time', 'desc')
            ->get()->toArray();
    }

    public function getDetail($userId, $collectMoneyStatus, $page, $limit)
    {
        $page -= 1;
        $page = $page < 0 ? 0 : $page;
        $offset = $page * $limit;
        return CollectMoneyBill::where('user_id', $userId)
            ->whereIn('collect_money_status', $collectMoneyStatus)
            ->offset($offset)
            ->limit($limit)
            ->orderBy('create_collect_time', 'desc')
            ->get();
    }

    public function getList($request)
    {
        $page = $request->pageNumber - 1;
        $page = $page < 0 ? 0 : $page;
        $limit = $request->pageSize ? $request->pageSize : 50;
        $offset = $page * $limit;
        $query = CollectMoneyBill::from('collect_money_bill as cmb')
            ->join('user_credit_card as cc', 'cmb.credit_card_id', '=', 'cc.id')
            ->join('user_bank_card as bc', 'cmb.bank_card_id', '=', 'bc.id')
            ->join('passage as p', 'cmb.passage_id', '=', 'p.id')
            ->select('cmb.*', 'cc.bank_no as credit_bank_no', 'cc.bank_description as credit_bank_description',
                'bc.bank_no as bank_no', 'bc.bank_description as bank_description',
                'p.id as passage_id', 'p.display_name as passage_name')
            ->where(function ($query) use ($request) {
                if (!empty($request->collect_money_status)) {
                    $query->where('cmb.collect_money_status', $request->collect_money_status);
                }
                if (!empty($request->passage_id)) {
                    $query->where('cmb.passage_id', $request->passage_id);
                }
                if (!empty($request->keyword)) {
                    switch ($request->field) {
                        case 'user_id':
                            $query->where('cmb.user_id', $request->keyword);
                            break;
                        case 'bill_id':
                            $query->where('cmb.id', $request->keyword);
                            break;
                        case 'bill_sn':
                            $query->where('cmb.bill_sn', 'like', '%' . $request->keyword . '%');
                            break;
                        case 'idcard_number':
                            $userId = User::where('idcard_number', $request->keyword)->value('user_id');
                            $query->where('cmb.user_id', $userId);
                            break;
                        case 'credit_card_no':
                            $creditCardId = UserCreditCard::where('bank_no', $request->keyword)->value('id');
                            $query->where('cmb.credit_card_id', $creditCardId);
                            break;
                        case 'bank_card_no':
                            $creditCardId = UserBankCard::where('bank_no', $request->keyword)->value('id');
                            $query->where('cmb.bank_card_id', $creditCardId);
                            break;
                        case 'credit_card_id':
                            $query->where('cmb.credit_card_id', $request->keyword);
                            break;
                        case 'bank_card_id':
                            $query->where('cmb.bank_card_id', $request->keyword);
                            break;
                    }
                }
                if (!empty($request->start_time) && !empty($request->end_time)) {
                    $query->whereBetween('cmb.create_collect_time', [strtotime($request->start_time), strtotime($request->end_time)]);
                }
            });
        $total = $query->count();
        $result = $query->latest('cmb.id')
            ->offset($offset)
            ->limit($limit)
            ->get();
        return ['result' => $result, 'count' => $total];
    }
}